/**
 * tjftp -- A simple FTP server, using the ANSI C
 * Copyright (C) 2011  degui.chen <degui.chen@qq.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "memory.h"
static int debut_mode = 0;
static char debug_log_path[] = "/tmp/memory_log.txt";
static FILE* fp;
static void _printf_debug_info(){
	printf("\n\n-----------------memory log path : %s\n\n", debug_log_path);
	if(fp != NULL){
		fclose(fp);
	}
}

void tj_memory_debug(){
	if(!debut_mode){
		debut_mode = 1;
		fp = fopen(debug_log_path, "w");	
		if (fp == NULL) {
			perror(debug_log_path);
			exit(-1);
		}			
		atexit(_printf_debug_info);
	}
}

void* _tj_memory_alloc(int size, const char* file, const char* fun, int line, int ansi_c) {
	void* lp = (float*) malloc(size);
	if (!lp) {
		perror("memory allocate fail.");
		exit(1);
	}
	if(debut_mode){
		char result[1024] = { '\0' };
		sprintf(result, "memory alloc -- %p ,file: %s, function: %s, line: %i, ANSI C: %i, size: %i \n", lp, file, fun, line, ansi_c, size);
		fputs(result, fp);
	}
	return lp;
}

void _tj_memory_free(void* lp, const char* file, const char* fun, int line, int ansi_c) {
	if(debut_mode){
		char result[1024] = { '\0' };
		sprintf(result, "memory  free -- %p ,file: %s, function: %s, line: %i, ANSI C: %i\n", lp, file, fun, line, ansi_c);
		fputs(result, fp);
	}
	free(lp);
	lp = NULL;
}


char* tj_memory_index_char(char* str, char key) {
	return (char *) memchr(str, key, strlen(str));
}

char* tj_memory_index_string(char* string, char* key, int position) {
	int key_length = strlen(key);
	char* result;
	for (result = string; result >= (string - key_length + position); result++) {
		if (memcmp(result, key, key_length) == 0){
			return result; /* found */
		}
	}
	return NULL;
}

int tj_memory_compare(const void *s1, const void *s2, size_t length) {
	return memcmp(s1, s2, length);
}

void tj_memory_copy(void *dest, const void *src, size_t length) {
	memcpy(dest, src, length);
}

void tj_memory_move(void * dest, const void * src, size_t length) {
	memmove(dest, src, length);
}

void tj_memory_clear(char* str, int length) {
	memset(str, '\0', length);
}
